package com.estore.service;

import com.estore.model.User;
import com.estore.model.UserRole;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户服务类，负责用户认证和权限管理
 */
public class UserService {
    // 模拟用户数据库
    private final Map<String, User> userDatabase = new HashMap<>();

    public UserService() {
        initializeDefaultUsers();
    }

    private void initializeDefaultUsers() {
        // 默认管理员账户
        userDatabase.put("admin", new User("admin", "admin123", UserRole.ADMIN));
        // 默认客户账户
        userDatabase.put("customer", new User("customer", "customer123", UserRole.CUSTOMER));
        userDatabase.put("alice", new User("alice", "alice123", UserRole.CUSTOMER));
        userDatabase.put("bob", new User("bob", "bob123", UserRole.CUSTOMER));
    }

    /**
     * 用户登录验证
     */
    public User login(String username, String password) {
        User user = userDatabase.get(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }


    /**
     * 注册新用户
     */
    public boolean register(String username, String password) {
        if (userDatabase.containsKey(username)) {
            return false; // 用户名已存在
        }
        userDatabase.put(username, new User(username, password, UserRole.CUSTOMER));
        return true;
    }

    /**
     * 检查用户权限
     */
    public boolean hasAdminPermission(User user) {
        return user != null && user.getRole() == UserRole.ADMIN;
    }
}